<template>
  <div class="app-container">
    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button type="success" icon="plus" @click="handleOpenDialog()">新增</el-button>
        </div>
      </div>
      <vxe-grid v-bind="gridOptions">
        <template #pager>
          <!--使用 pager 插槽-->
          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handlePageChange"
          />
        </template>
        <template #status="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
            {{ scope.row.status == 1 ? "正常" : "禁用" }}
          </el-tag>
        </template>
        <template #time="scope">
          {{ formatDate(scope.row[scope.column.field]) }}
        </template>
        <template #operate="scope">
          <el-button
            type="primary"
            icon="edit"
            link
            size="small"
            @click="handleOpenDialog(scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            link
            size="small"
            icon="delete"
            @click.stop="handleStatusChange(scope.row)"
          >
            {{ scope.row.status == 1 ? "冻结" : "激活" }}
          </el-button>
        </template>
      </vxe-grid>

      <!-- 用户表单 -->
      <el-drawer
        v-model="dialog.visible"
        :title="dialog.title"
        append-to-body
        @close="handleCloseDialog"
      >
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
          <el-form-item label="产品料号" prop="product">
            <el-input v-model="formData.product" placeholder="产品料号" :disabled="true" />
          </el-form-item>
          <el-form-item label="生产线体" prop="line">
            <el-input v-model="formData.line" placeholder="生产线体" />
          </el-form-item>
          <el-form-item label="UPH" prop="uph">
            <el-input v-model="formData.uph" placeholder="请输入小时产能" style="width: 100px" />
            <span class="mx-1">{{ unit_name }}</span>
          </el-form-item>
          <el-form-item label="人员数量" prop="staff">
            <el-input
              v-model="formData.staff"
              placeholder="请输入需求人员数量"
              style="width: 100px"
            />
            <span class="mx-1">人</span>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
            <el-button @click="handleCloseDialog">取 消</el-button>
          </div>
        </template>
      </el-drawer>
    </el-card>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ProductManagement",
  inherititems: false,
});
import { formatDate } from "@/utils/tools";
import ProductManagementAPI, {
  MaterialOptionType,
  ProductManagementPageQuery,
  ProductManagementPageVO,
  ProductManagementForm,
} from "@/api/product/management";
import ProductAPI from "@/api/product/product";
const route = useRoute();
const product = ref(route.query.product as unknown as string);
const queryParams = reactive<ProductManagementPageQuery>({
  pageNum: 1,
  pageSize: 10,
  product: product.value,
});
const unit_name = ref("");
const total = ref(0);
const formRef = ref(ElForm);
const dialog = reactive({
  visible: false,
  title: "新增生产信息",
});
const materialOptions = ref<MaterialOptionType[]>();
const formData = reactive<Partial<ProductManagementForm>>({});
const initFormData: Partial<ProductManagementForm> = {
  id: undefined,
  product: product.value,
  uph: 0,
  unit_name: "",
  line: "",
  staff: 0,
  is_update: false,
};
const rules = reactive({
  id: [
    {
      pattern: /(^[A-Za-z0-9_-]{4,15}$)/,
      message: "请输入产品编号",
      trigger: "blur",
    },
    { required: true, message: "编号不能为空", trigger: "blur" },
  ],
  product: [{ required: true, message: "编号不能为空", trigger: "blur" }],
  material: [{ required: true, message: "材料不能为空", trigger: "blur" }],
  // UPH 需＞0的正整数
  uph: [
    { required: true, message: "UPPH不能为空", trigger: "blur" },
    { pattern: /(^[1-9]\d*$)/, message: "UPPH必须为正整数", trigger: "blur" },
  ],
  line: [{ required: true, message: "产线不能为空", trigger: "blur" }],
  staff: [
    { required: true, message: "人数不能为空", trigger: "blur" },
    { pattern: /(^[1-9]\d*$)/, message: "人数必须为正整数", trigger: "blur" },
  ],
});
// 监听路由参数变化，更新字典数据
watch(
  () => [route.query.product],
  ([newProduct]) => {
    queryParams.product = newProduct as string;
    product.value = newProduct as string;
    initFormData.unit_name = (route.query.unit_name as string) || "";
    // handleQuery();
  }
);
const remoteMethod = async (query: string) => {
  if (query) {
    let options = await ProductAPI.getOptions(query);
    // 将options的label修改为value+label
    options.forEach((item: OptionType) => {
      item.label = `${item.value},${item.label}`;
    });
    // 将options的value为product.value的项目删除
    options = options.filter((item: OptionType) => item.value !== product.value);
    materialOptions.value = options;
  } else {
    materialOptions.value = [];
  }
};
const handleChange = (value: string) => {
  unit_name.value = materialOptions.value?.find((item) => item.value === value)?.unit_name || "";
};
async function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改生产信息";
    formData.is_update = true;
    ProductManagementAPI.getFormData(id).then((data) => {
      Object.assign(formData, { ...data });
      unit_name.value = (data as any).unit_name || "";
    });
  } else {
    Object.assign(formData, initFormData);
    dialog.title = "新增生产信息";
  }
}
// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  formData.id = undefined;
}
const handlePageChange: typeof VxePagerEvents.PageChange = ({
  currentPage,
  pageSize,
}: {
  currentPage: number;
  pageSize: number;
}) => {
  queryParams.pageNum = currentPage;
  queryParams.pageSize = pageSize;
  handleQuery();
};
// 查询
function handleQuery() {
  gridOptions.loading = true;
  ProductManagementAPI.getPage(queryParams)
    .then((data) => {
      gridOptions.data = data.list;
      total.value = data.total;
    })
    .finally(() => {
      gridOptions.loading = false;
    });
}
// 提交用户表单（防抖）
const handleSubmit = useDebounceFn(() => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const product_id = formData.id as number;
      if (formData.is_update) {
        ProductManagementAPI.update(product_id, formData)
          .then(() => {
            ElMessage.success("修改产品成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => {
            gridOptions.loading = false;
          });
      } else {
        ProductManagementAPI.add(formData)
          .then(() => {
            ElMessage.success("新增产品成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => {
            gridOptions.loading = false;
          });
      }
    }
  });
}, 1000);
// 重置查询
function handleResetQuery() {
  queryParams.pageNum = 1;
  handleQuery();
}
// 删除系统配置
function handleDelete(id: number) {
  ElMessageBox.confirm("确认删除该项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    ProductManagementAPI.deleteByIds(id as unknown as string).then(() => {
      ElMessage.success("删除成功");
      // handleQuery();
      handleResetQuery();
    });
  });
}
// 激活事件，将部门状态进行修改
function handleStatusChange(row: ProductManagementPageVO) {
  const text = row.status == 0 || row.status == 2 ? "启用" : "停用";
  ElMessageBox.confirm(`确认要${text}该条信息吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    let status = row.status == 0 || row.status == 2 ? 1 : 2;
    ProductManagementAPI.update(row.id as number, {
      status: status,
    }).then(() => {
      row.status = status;
      ElMessage.success(`${text}成功`);
    });
  });
}
const gridOptions = reactive<typeof VxeGridProps<ProductManagementPageVO>>({
  border: true,
  loading: false,
  columns: [],
  id: "product-management",
  data: [],
  columnConfig: {
    resizable: true,
  },
  customConfig: {
    enabled: true,
    storage: {
      resizable: true,
    },
  },
});

// 列配置
gridOptions.columns = [
  { field: "product", title: "产品" },
  { field: "line", title: "线体" },
  { field: "uph", title: "产能(H)" },
  { field: "unit_name", title: "单位" },
  { field: "staff", title: "人员数量" },
  { field: "status", title: "状态", width: 80, slots: { default: "status" } },
  { field: "create_time", title: "建立时间", width: 100, slots: { default: "time" } },
  { field: "update_time", title: "更新时间", width: 100, slots: { default: "time" } },
  { field: "create_user", title: "建立人员", width: 100 },
  { field: "update_user", title: "更新人员", width: 100 },
  { title: "操作", width: 150, slots: { default: "operate" } },
];
onMounted(async () => {
  handleQuery();
});
</script>

<style scoped></style>
